package com.lmx.smsmonitor.javamail;


import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class MailSendHelper {

    private static Message getMessage(MailSenderInfo mailInfo) throws UnsupportedEncodingException, MessagingException {
        Session session = Session.getDefaultInstance(mailInfo.getProperties(), mailInfo.getAuthenticator());
        session.setDebug(mailInfo.isDebugMode());
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailInfo.getFromAddress()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailInfo.getToAddress()));
        // 判断抄送是否为null和空
        if (StringUtils.isNotBlank(mailInfo.getCcAddress())) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(mailInfo.getCcAddress()));
        }
        if (StringUtils.isNotBlank(mailInfo.getBccAddress())) {
            message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mailInfo.getBccAddress()));
        }
        message.setSubject(MimeUtility.encodeText(mailInfo.getSubject(), "utf-8", "B"));
        message.setSentDate(new Date());
        return message;
    }

    public static boolean sendTextMail(MailSenderInfo mailInfo) {
        try {
            Message message = getMessage(mailInfo);
            message.setText(mailInfo.getContent());
            message.saveChanges();
            Transport.send(message);
            return true;
        } catch (MessagingException | UnsupportedEncodingException e) {
            System.out.println(e.getMessage());
        }
        return false;
    }

    public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
        try {
            Message message = getMessage(mailInfo);
            message.setContent(mailInfo.getContent(), "text/html;charset=UTF-8");
            message.saveChanges();
            Transport.send(message);
            return true;
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }


}
